package com.xunmall.common.interceptor;

import com.xunmall.base.annotation.AutoIdempotent;
import com.xunmall.base.dto.Result;
import com.xunmall.base.util.JsonUtils;
import com.xunmall.common.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * @author wangyanjing
 * @date 2020/4/13
 */
@Component
public class AutoIdempotentInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 被ApiIdempotent标记的扫描
        AutoIdempotent autoIdempotent = method.getAnnotation(AutoIdempotent.class);
        if (autoIdempotent != null) {
            try {
                return tokenService.checkToken(httpServletRequest);
            } catch (Exception ex) {
                Result result = Result.ofParamsError("token校验异常");
                writeReturnJson(httpServletResponse, JsonUtils.toJson(result));
                throw ex;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    private void writeReturnJson(HttpServletResponse response, String param) throws Exception {
        PrintWriter printWriter = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        try {
            printWriter = response.getWriter();
            printWriter.write(param);
        } catch (Exception ex) {
        } finally {
            if (printWriter != null) {
                printWriter.close();
            }
        }

    }
}
